package com.github.nacostwo.service.impl;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import com.github.nacostwo.entity.EsBook;
import com.github.nacostwo.repository.EsBookRepository;
import com.github.nacostwo.service.EsBookService;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class EsBookServiceImpl implements EsBookService {

    @Autowired
    private EsBookRepository esBookRepository;

    @Override
    public void delete(String id) {
        esBookRepository.deleteById(id);
    }

    @Override
    public EsBook create(String id) {
        EsBook book = new EsBook();
        book.setId(id);
        book.setName("test-book");
        book.setDesc("test desc");
        esBookRepository.save(book);
        return book;
    }

    @Override
    public Page<EsBook> search(String name, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        QueryBuilder query = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("name", name))
                .must(QueryBuilders.matchQuery("desc", name));

        //return esBookRepository..search(query, pageable);
        return null;
    }

    @Override
    public List<EsBook> searchAll() {
        Iterable<EsBook> iterable = esBookRepository.findAll();
        Iterator<EsBook> iterator = iterable.iterator();
        List<EsBook> list = new ArrayList<EsBook>();
        for(int i=0;iterator.hasNext() && i<10;i++) {
            list.add(iterator.next());
        }
        return list;
    }

}
